<template lang="pug">
  section
    show-table(ref='tab',:total='total',:current='current',:columns='columns',:data='accountData',@handleChangePage='handleChangePage')
    Modal(v-model="acountModel",:title="modelTitle",@on-cancel='handleCancel',transfer).account-modal
      Form(ref="accountForm",:model="formValidate",:rules='ruleValidate',:label-width="100")
        FormItem(v-for="(item, index) in formValidate.items",:prop="'items.' + index + '.value'",label='请求参数：',:key="index").form-item-reset
          Row
            Col(span='19')
              Input(v-model='item.value',placeholder='接口请求参数')
            Col(span='4')
              Button(v-if="index>0",@click='handleDeleteItem(index)',style='marginLeft:10px') 删除
        FormItem.form-item-reset
          Button(type="dashed",icon="plus-round",@click='handleAddParams') 添加参数
        FormItem(label="站点域名：",prop="site_Domain").form-item-reset
          Input(placeholder='请输入站点域名',v-model="formValidate.site_Domain",:maxlength="100")
        FormItem(label="是否可用：",prop="account_Status",style='margin-bottom:0')
          RadioGroup(v-model="formValidate.account_Status")
            Radio(:label="1") 是
            Radio(:label="0") 否
      template(slot="footer")
        Button(@click="handleCancel") 取消
        Button(type='primary', @click="handleSave") 保存
</template>

<script>
import showTable from '@/components/show-table/show-table'
import { asyncSite } from '../../api'

export default {
  components: { showTable },
  data() {
    return {
      index: 1,
      formValidate: {
        items: [{ value: '', index: 1 }],
        site_Domain: '',
        account_Status: 1
      },
      ruleValidate: {
        site_Domain: [{ required: true, message: '请输入站点域名', trigger: 'blur' }, { type: 'url', message: '站点域名格式错误,非正确域名格式', trigger: 'blur' }]
      },
      accountId: '',
      acountModel: false,
      modelTitle: '新建账号配置',
      total: 0,
      current: 1,
      accountData: [],
      columns: [
        { title: 'ID', width: 60, align: 'center', key: 'id' },
        {
          title: '账号域名',
          align: 'center',
          render: (h, params) => {
            return h(
              'span',
              {
                style: { color: '#2d8cf0', cursor: 'pointer' },
                on: {
                  click: () => {
                    this.acountModel = true
                    this.modelTitle = '修改账号配置'
                    this.formValidate.items = params.row.parameter.split('&`~`&').map(item => {
                      return { value: item }
                    })
                    ;({ row: { site_Domain: this.formValidate.site_Domain, account_Status: this.formValidate.account_Status, id: this.accountId } } = params)
                  }
                }
              },
              params.row.site_Domain
            )
          }
        },
        {
          title: '账号状态',
          align: 'center',
          render: (h, params) => {
            const createElement = text => {
              return h('p', [h('Icon', { style: { marginRight: '5px', color: '#3dbd7d' }, attrs: { type: 'record' } }), h('span', text)])
            }
            switch (params.row.account_Status) {
              case 0:
                return createElement('过期')
              case 1:
                return createElement('在用')
            }
          }
        },
        {
          title: '操作',
          width: 90,
          align: 'center',
          render: (h, params) => {
            return h(
              'Poptip',
              {
                attrs: { confirm: true, title: '确定要删除这条配置吗?', placement: 'top-end', width: 200 },
                on: { 'on-ok': () => this.handleAccountDelete(params.row.id, params.index) }
              },
              [h('Button', { attrs: { icon: 'md-trash', title: '删除' }, style: { color: '#f04134' }, class: { 'operate-btn': true } })]
            )
          }
        }
      ]
    }
  },
  mounted() {
    this.handleAccountTableData()
  },
  methods: {
    handleChangePage(pageSub) {
      this.handleUpdateTableData(pageSub)
    },
    handleUpdateTableData(current = 1) {
      this.current = current
      this.handleAccountTableData()
    },
    handleAccountTableData: async function() {
      try {
        this.total = 0
        this.accountData = []
        this.$refs['tab'].loading = true
        const res = await asyncSite.accountlist({ data: { siteId: this.$route.query.siteId, pageIndex: this.current, pageSize: this.$refs['tab'].pageSize } })
        this.total = res.data.data.recordCount
        this.accountData = res.data.data.result
        this.$refs['tab'].loading = false
      } catch (error) {
        this.$refs['tab'].loading = false
      }
    },
    handleAddParams() {
      this.index++
      this.formValidate.items.push({ value: '', index: this.index })
    },
    handleDeleteItem(index) {
      this.formValidate.items.splice(index, 1)
    },
    handleAccountDelete: async function(id, index) {
      try {
        await asyncSite.deleteaccount({ data: { id } })
        this.accountData.splice(index, 1)
        this.handleUpdateTableData(this.accountData.length !== 0 ? this.current : --this.current !== 0 ? this.current : (this.current = 1))
        this.$Message.success('删除成功')
      } catch (error) {}
    },
    handleSave() {
      this.$refs['accountForm'].validate(async valid => {
        if (valid) {
          let parameter = ''
          this.formValidate.items.forEach((item, index) => {
            if (index === this.formValidate.items.length - 1) parameter = parameter + item.value
            else parameter = parameter + item.value + '&`~`&'
          })
          try {
            const { site_Domain, account_Status } = this.formValidate
            if (this.modelTitle === '新建账号配置') await asyncSite.addaccount({ data: { parameter, site_Domain, account_Status, site_Id: this.$route.query.siteId } })
            else await asyncSite.updateAccount({ data: { parameter, site_Domain, account_Status, id: this.accountId, site_Id: this.$route.query.siteId } })
            this.acountModel = false
            this.handleUpdateTableData()
            this.$refs['accountForm'].resetFields()
          } catch (error) {}
        }
      })
    },
    handleCancel() {
      this.acountModel = false
      this.$refs['accountForm'].resetFields()
      this.formValidate.items = [{ value: '', index: 1 }]
    }
  }
}
</script>
